import modelExtend from 'dva-model-extend'
import { contractListInProduction, tms, ins } from './services/contractOrders'
import { contractOrderDetail, acceptOmsQuote, editOuterLogistics, queryLogisticCompany } from './services/order'
import { lwjPageModel } from 'utils/model'
import { logisticsStatus, logisticsCancelStatus } from 'utils/enumConfig'
import { message } from 'antd'

export default modelExtend(lwjPageModel, {
  namespace: 'contractInProduction',
  state: {
    items: [],
    currentContractDetail: {},
    currentLogisticsDetail: {},
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    isExpand: false,
    queryParam: {},
    isShowContractDetailModal: false,
    logisticsDetailModalVisible: false,
    logisticsSummaries: [],
    installationSummaries: {},
    spinLoading: false,
    isHashProduction:false,
    outerLogistics: {},
    logisticCompanys: [],
    outerLogisticsModalVisible: false,
    filterLogisticCompanys: []
  },
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname}) => {
        if (pathname === '/order/inProduction') {
          dispatch({type: 'query', payload: {}})
          dispatch({type: 'queryLogisticCompany'})
        }
      })
    },
  },
  effects: {
    * query ({payload}, {call, put, select}) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      })
      const pageOptions = yield select(({contractInProduction}) => contractInProduction.pageOptions)
      const queryParam = yield select(({contractInProduction}) => contractInProduction.queryParam)
      const queryPayload = {
        ...pageOptions,
        queryParam: queryParam
      }
      const data = yield call(contractListInProduction, queryPayload)
      // 处理物流数据
      _.each(data.content, (item) => {
        /** @namespace item.logisticsOrderStatuses */
        if (Array.isArray(item.logisticsOrderStatuses)) {
          let logisticsStatusArr = item.logisticsOrderStatuses
            .map((order) => {
              return order.cancelStatus === 'NONE' ? logisticsStatus[order.logisticStatus] : logisticsCancelStatus[order.cancelStatus]
            })
          item.logisticsStatus = logisticsStatusArr.join(',')
        } else {
          item.logisticsStatus = '已生产'
        }
      })
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * onShowDetail ({
                      payload
                    }, {select, call, put}) {
      const data = yield call(contractOrderDetail, payload.salesOrderId, payload.contractOrderId)
      yield put({
        type: 'detailSuccess',
        payload: {
          currentContractDetail: data.result,
        }
      })
      yield put({type: 'showContractDetailModal', payload: {}})
      yield put({
        type: 'setSpinLoading', payload: {
          spinLoading: false
        }
      })
      yield put({
        type: 'setLogisticsSummaries',
        payload: data.result
      })
    },
    * getTms ({
                payload
              }, {select, call, put}) {
      const {id} = payload
      const data = yield call(tms, id)
      const logisticsSummaries = _.isEmpty(data.result.logisticsOrderSummaries) ? [] : data.result.logisticsOrderSummaries

      yield put({
        type: 'detailSuccess',
        payload: {
          logisticsSummaries: logisticsSummaries
        }
      })
      yield put({
        type: 'setCurrentLogisticsDetail',
        payload: logisticsSummaries[0]
      })
    },
    * getIns ({
                payload
              }, {select, call, put}) {
      const {id} = payload
      const data = yield call(ins, id)

      yield put({
        type: 'detailSuccess',
        payload: {
          installationSummaries: data.result.installDetail,
          spinLoading: false
        }
      })
    },
    * editOuterLogistics({params}, {select, call, put}){
      const {result: data} = yield call(editOuterLogistics, params);
      message.success("保存成功");
      yield put({
        type: 'toggleOuterLogisticsVisible',
        outerLogisticsModalVisible: false
      })
      const pageOptions = yield select(({contractInProduction}) => contractInProduction.pageOptions)
      const queryParam = yield select(({contractInProduction}) => contractInProduction.queryParam)
      yield put({
        type: 'query',
        payload: {
          ...pageOptions,
          ...queryParam
        }
      })
    },
    * queryLogisticCompany({}, {select, call, put}){
      const {result: data} = yield call(queryLogisticCompany);
      let _filterLogisticCompanys = [{name: '全部', value: ''}];
      if(data){
        data.forEach(val => {
          _filterLogisticCompanys.push({
            name: val.companyName,
            value: val.companyCode
          })
        })
      }
      yield put({
        type: 'setLogisticCompanys',
        logisticCompanys: data ? data : []
      })
      yield put({
        type: 'setFilterLogisticCompanys',
        filterLogisticCompanys: _filterLogisticCompanys
      })
    },
  },
  reducers: {
    expandFilter (state, {payload}) {
      return {
        ...state,
        isExpand: true
      }
    },
    unExpandFilter (state, {payload}) {
      return {
        ...state,
        isExpand: false
      }
    },
    detailSuccess (state, {payload}) {
      return {
        ...state,
        ...payload
      }
    },
    showContractDetailModal (state, {payload}) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: true
      }
    },
    showLogisticsDetailModalVisible (state, {payload}) {
      return {
        ...state,
        ...payload,
        logisticsDetailModalVisible: true
      }
    },
    hideContractDetailModal (state, {payload}) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: false
      }
    },
    hideLogisticsDetailModalVisible (state, {payload}) {
      return {
        ...state,
        ...payload,
        logisticsDetailModalVisible: false
      }
    },
    setLogisticsSummaries (state, {payload}) {
      return {
        ...state,
        ...payload,
        logisticsSummaries: payload.logisticsOrderSummaries
      }
    },
    setSpinLoading (state, {payload}) {
      return {
        ...state,
        ...payload,
        spinLoading: payload.spinLoading
      }
    },
    setIsHashProduction (state, {payload}) {
      return {
        ...state,
        ...payload,
        isHashProduction: payload
      }
    },

    setCurrentLogisticsDetail: function (state, {payload}) {
      if (_.isEmpty(payload)) {
        return {
          ...state,
          ...payload,
          currentLogisticsDetail: {}
        }
      }
      /** @namespace payload.allRoutes*/
        // 拼装ROUTE信息
      let route = []
      let activities = []
      if (!_.isEmpty(payload) && Array.isArray(payload.allRoutes)) {
        payload.allRoutes.sort((a, b) => {
          return a.rindex - b.rindex
        })
        payload.allRoutes.forEach((item) => {
          /** @property item.rindex */
          route.push(item.origin)
          route.push(item.destination)
          /** @namespace item.activities */
          item.activities.sort((a, b) => a.createTime - b.createTime).forEach((activity, index) => {
            let datum = {
              creatorName: activity.creatorName,
              action: activity.action,
              memo: activity.memo,
              createTime: activity.createTime
            }
            if (index === 0) {
              datum.origin = item.origin
            } else {
              datum.origin = null
            }
            activities.push(datum)
          })
        })
      }
      let routeSet = new Set(route)
      payload.route = Array.from(routeSet).join('-')
      payload.activities = activities

      return {
        ...state,
        ...payload,
        currentLogisticsDetail: payload
      }
    },

    toggleOuterLogisticsVisible(state, {outerLogisticsModalVisible}) {
      return{
        ...state,
        outerLogisticsModalVisible
      }
    }, 
    setOuterLogistics(state, {outerLogistics}) {
      return{
        ...state,
        outerLogistics
      }
    }, 
    setLogisticCompanys(state, {logisticCompanys}) {
      return{
        ...state,
        logisticCompanys
      }
    }, 
    setFilterLogisticCompanys(state, {filterLogisticCompanys}) {
      return{
        ...state,
        filterLogisticCompanys
      }
    }, 
  }
})
